"use-strict"
function ParallelFileWriter(entry) {
  this.fileEntry = entry;
  this.fileReceived = false;
  //this.onComplete = onComplete;
  //this.onComplete = oneComplete;
  this.position = 0;
  this.workingWriters = 0;
  this.writers = [];

}

ParallelFileWriter.prototype.getWriter = function() {
  var self = this;
  return new Promise(function (resolve, reject) {
    if (self.writers.length > 0) {
      self.workingWriters++;
      resolve(self.writers.shift());
    }
    else {
      self.fileEntry.createWriter(function (fileWriter) {
        self.workingWriters++;
        resolve(fileWriter);
      }, reject);
    }
	});
};

ParallelFileWriter.prototype.restoreWriter = function(writer) {
  this.writers.push(writer);
  this.workingWriters--;
};

ParallelFileWriter.prototype.write = function (data, callback) {
  var self = this;
  var curPosition = self.position;
  self.position += data.byteLength;
  self.getWriter().then(function (writer) {
    var blob = new Blob([data]);
    writer.seek(curPosition);
    writer.write(blob);
    writer.onwrite = function() {
      self.restoreWriter(writer);
      callback();
    };
    writer.onerror = FTPUI.notifyUI;
  }).catch(function (error) {
    FTPUI.notifyUI("file saving problem " + error);
  });
};





